package com.tanhua.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.Announcement;
import com.tanhua.model.domain.User;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.*;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.MessageService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.management.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private AnnouncementsApi announcementsApi;

    /**
     * 通过环信id查询用户信息
     * @param huanxinId
     * @return
     */
    @Override
    public UserInfoVo findUserInfoByHuanxinId(String huanxinId) {
        User user = userApi.findByhuanxinId(huanxinId);
        UserInfo info = userInfoApi.findById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(info,vo);
        if (info.getAge()!=null){
            vo.setAge(info.getAge().toString());  //userInfo中的age是Integer类型，userInfoVo中的age是String类型
        }
        return vo;
    }

    /**
     * 添加好友
     * @param friendId
     */
    @Override
    public void contacts(Long friendId) {
        //将好友关系注册到环信
        Boolean flag = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + friendId);
        if (!flag){
            throw new BusinessException(ErrorResult.error());
        }
        //将好友关系保存到MongoDB
        friendApi.save(friendId,UserHolder.getUserId());
    }

    @Override
    public PageResult findFriends(Integer page, Integer pagesize, String keyword) {
        //调用api查询当前用户的好友数据
        List<Friend> friendList = friendApi.findById(UserHolder.getUserId(),page,pagesize);
        //提取好友列表中的好友id
        if (CollUtil.isEmpty(friendList)){
            return new PageResult();
        }

        //根据好友的id去查询好友的详细信息
        List<Long> friendIds = CollUtil.getFieldValues(friendList, "friendId", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        Map<Long, UserInfo> map = userInfoApi.findByIds(friendIds, userInfo);
        List<ContactVo> voList = new ArrayList<>();
        for (Friend friend : friendList) {
            UserInfo info = map.get(friend.getFriendId());
            if (info!=null){
                ContactVo vo = ContactVo.init(info);
                voList.add(vo);
            }
        }
        return new PageResult(page,pagesize,0L,voList);
    }

    /**
     * 分页查询评论列表
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findComments(Integer page, Integer pagesize) {
        Long id = UserHolder.getUserId();
        //根据发布人和评论类型去查找
        List<Comment> comments = commentApi.findComments(id,CommentType.COMMENT,page,pagesize);
        //获取评论列表的所有参与评论的用户ID
        if (CollUtil.isEmpty(comments)){
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo!=null){
                CommentVo vo = CommentVo.init(userInfo, comment);
                voList.add(vo);
            }
        }
        return new PageResult(page,pagesize,0L,voList);
    }

    /**
     * 分页查询点赞列表
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findLikes(Integer page, Integer pagesize) {
        List<Comment> comments = commentApi.findComments(UserHolder.getUserId(), CommentType.LIKE, page, pagesize);
        //获取评论列表的所有参与评论的用户ID
        if (CollUtil.isEmpty(comments)){
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo!=null){
                CommentVo vo = CommentVo.init(userInfo, comment);
                voList.add(vo);
            }
        }
        return new PageResult(page,pagesize,0L,voList);
    }

    @Override
    public PageResult findLoves(Integer page, Integer pagesize) {
        List<Comment> comments = commentApi.findComments(UserHolder.getUserId(), CommentType.LOVE, page, pagesize);
        //获取评论列表的所有参与评论的用户ID
        if (CollUtil.isEmpty(comments)){
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo!=null){
                CommentVo vo = CommentVo.init(userInfo, comment);
                voList.add(vo);
            }
        }
        return new PageResult(page,pagesize,0L,voList);
    }

    @Override
    public PageResult announcements(Integer page, Integer pagesize) {
        Page<Announcement> page1 = announcementsApi.findAllAnnouncements(page, pagesize);
        List<Announcement> list = page1.getRecords();
        if(CollUtil.isEmpty(list)){
            return new PageResult();
        }
        List<AnnouncementVo> voList = new ArrayList<>();

        for (Announcement announcement : list) {
            AnnouncementVo vo = new AnnouncementVo();
            BeanUtils.copyProperties(announcement,vo);
            vo.setCreateDate(String.valueOf(System.currentTimeMillis()));
            voList.add(vo);
        }
        return new PageResult(page,pagesize,page1.getTotal(),voList);
    }

    /**
     * 删除好友
     * @param notLikeuserId
     */
    @Override
    public void delete(Long notLikeuserId) {
        //删除好友
        friendApi.delete(UserHolder.getUserId(),notLikeuserId);
        //删除环信好友
        Boolean flag = huanXinTemplate.deleteContact(Constants.HX_USER_PREFIX + UserHolder.getUserId(), Constants.HX_USER_PREFIX + notLikeuserId);
    }

}
